<template>
  <div class="data-container">
    <!-- 条件查询 -->
    <el-card style="margin-bottom: 5px">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <span class="query_con">用户名称 </span>
          <el-input
              v-model="queryParams.username"
              placeholder="用户名"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 操作区 -->
    <el-card>
      <template #header>
        <el-button type="primary" @click="openDialog()">
          <el-icon>
            <Plus/>
          </el-icon>
          新增用户
        </el-button>
      </template>
      <!-- 用户列表数据 -->
      <el-table
          :data="pageData"
          v-loading="loading"
          border
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333', fontWeight: 'bold' }">
        <el-table-column prop="userId" align="center" label="ID"/>
        <el-table-column prop="username" align="center" label="用户名称"/>
        <el-table-column prop="age" align="center" label="年龄"/>
        <el-table-column prop="sex" align="center" label="性别"/>
        <el-table-column prop="createTime" align="center" label="创建时间"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="userDetail(scope.row.userId)">详情</el-button>
            <el-button type="primary" size="small" @click="userDelete(scope.row.userId)">删除</el-button>
            <el-button type="primary" size="small" @click="openDialog(scope.row.userId)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        :width="dialog.width"
        append-to-body
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
          v-if="dialog.type === 'user-form'"
          ref="userFormRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="ID" prop="userId">
          <el-input :value="formData.userId" :readonly="true"/>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input ref="username" name="username" v-model="formData.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input ref="age" name="age" v-model="formData.age" placeholder="请输入用户年龄"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input ref="sex" name="sex" v-model="formData.sex" placeholder="请输入用户性别"/>
        </el-form-item>
        <el-form-item label="创建日期" prop="createTime">
          <el-input :value="formData.createTime" :readonly="true"/>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
import {UserForm, UserPageVO, UserQuery} from "@/api/user/model";
import UserAPI from "@/api/user/index";
import {ComponentSize, ElInput, ElMessage} from 'element-plus'

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单

const currentPage = ref(1)
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const loading = ref(false); //  加载状态
const isLoading = ref(false); //  加载状态

// 用户表单数据
const formData = reactive<UserForm>({});

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  isLoading.value = true;
  userFormRef.value.validate((valid: any) => {
    console.log("编辑表单验证通过", valid)
    // 模拟耗时请求
    handleQuery((data) => {
      isLoading.value = false;
      closeDialog();
      ElMessage.success("操作成功");
    })
  });
}, 3000);

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  // 用户表单弹窗
  if (id) {
    dialog.title = "修改用户";
    UserAPI.getInfo(id).then((data) => {
      Object.assign(formData, {...data.data});
      console.log("用户表单数据", formData, data.data);
    });
  } else {
    dialog.title = "新增用户";
  }
}

/**
 * 关闭弹窗
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  console.log("关闭弹窗");
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 400,
  title: "",
});

const rules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: "用户名不能为空",
      },
    ],
    age: [
      {
        required: true,
        trigger: "blur",
        message: "用户年龄不能为空",
      },
    ],
    sex: [
      {
        required: true,
        trigger: "blur",
        message: "用户性别不能为空",
      },
    ]
  };
});

// 分页插件相关函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  queryParams.pageSize = val;
  handleQuery()
}
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  console.log(`current page: ${val}`)
  handleQuery()
}
// 查询条件
const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  username: "admin",
});

const total = ref(0); // 数据总数
const pageData = ref<UserPageVO[]>(); // 用户分页数据
// 分页查询
function handleQuery(callback?: (data: any) => void) {
  console.log("查询条件", queryParams);
  loading.value = true;
  UserAPI.getPage(queryParams)
      .then((response) => {
        if(!response.data){
          return;
        }
        pageData.value = response.data;
        total.value = response.total;
        currentPage.value = queryParams.pageNum;
        pageSize.value = queryParams.pageSize;
        // 调用回调函数，传递响应数据
        if (callback && callback instanceof Function) {
          callback(response.data);
        }
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.username = "";
  handleQuery();
}

// 详情
function userDetail(id: number) {
  console.log("用户详情", id);
}

// 删除
function userDelete(id: number) {
  console.log("删除用户", id);
}

onMounted(() => {
  handleQuery();
});
</script>
<style scoped>
.data-container {
  background-color: white;
  padding-top: 5px;
  border-radius: 5px;
}

.pagination {
  padding: 10px 10px 10px 0px;
  display: flex;
  justify-content: flex-end;
}

.query_con {
  margin-right: 10px;
  font-weight: bold;
}
</style>